﻿#include "widget.h"
#include "ui_widget.h"
#include <QSerialPortInfo>
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        ui->portCombo->addItem(info.portName());
    }
    ui->sendButton->setEnabled(false);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_openButton_clicked()
{
    if (ui->openButton->text() == "Open")
    {
        port = new QSerialPort(this);
        port->setPortName(ui->portCombo->currentText());
        port->setBaudRate(ui->speedCombo->currentText().toInt(), QSerialPort::AllDirections);
        if (!port->open(QIODevice::ReadWrite))
        {
            port->deleteLater();
            return;
        }
        ui->portCombo->setEnabled(false);
        ui->speedCombo->setEnabled(false);
        ui->openButton->setText("Close");
        ui->sendButton->setEnabled(true);
        connect(port, &QSerialPort::readyRead,
                this, &Widget::on_readyRead);
        port->waitForReadyRead(1);
    }
    else
    {
        port->close();
        ui->portCombo->setEnabled(true);
        ui->speedCombo->setEnabled(true);
        ui->openButton->setText("Open");
        ui->sendButton->setEnabled(false);
        port->deleteLater();
    }
}

void Widget::on_readyRead()
{
    ui->recvEdit->moveCursor(QTextCursor::End);
    ui->recvEdit->insertPlainText(QString(port->readAll()));
}

void Widget::on_sendButton_clicked()
{
    QString msg = ui->msgEdit->text() + "\r";
    port->write(msg.toLocal8Bit());
}
